const http = require('http')
const path = require('path')
const fs = require('fs')

const conf = {
  root: './',
  port: 8989,
  hostname: '127.0.0.1'
}

const server = http.createServer((req, res) => {
  const filePath = path.join(conf.root, req.url)

  if (req.url === '/favicon.ico') {
    return res.end('');
  }

  fs.stat(filePath, (err, stats) => {
    if (err) {
      res.statusCode = 404
      res.setHeader('Content-text', 'text/plain')
      res.end(`${filePath} is not a directoru or file`)
      return;
    }

    // 如果是一个文件
    res.statusCode = 200
    res.setHeader('Content-text', 'text/plain')
    fs.createReadStream(filePath).pipe(res)
  })
})

server.listen(conf.port, conf.hostname, () => {
  const addr = `http:${conf.hostname}:${conf.port}`
  console.info(`run at ${addr}`)
})